﻿using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;

namespace Md.Demo.Entity.MongoModels
{
    public class MongoContext
    {
        private readonly MongoOptions mongoOptions = new MongoOptions();
        private readonly MongoClient mongoClient;
        public IMongoDatabase MongoDatabase { get; }

        public MongoContext(IConfiguration config)
        {
            this.mongoOptions.Database = config.GetSection("MongoOptions:Database").Value;
            this.mongoOptions.Url = config.GetSection("MongoOptions:Url").Value;
            MongoClientSettings mongoClientSettings = MongoClientSettings.FromUrl(new MongoUrl(mongoOptions.Url));

            mongoClient = new MongoClient(mongoClientSettings);
            MongoDatabase = mongoClient.GetDatabase(mongoOptions.Database);
        }
        public IMongoCollection<T> Collection<T>() where T : class
        {
            return MongoDatabase.GetCollection<T>(typeof(T).Name);
        }
    }

    public static class MongoCollectionExtensions
    {
        public static DeleteResult DeleteOneById<T>(this IMongoCollection<T> collection, string id) where T : DocumentBase
        {
            return collection.DeleteOne(Builders<T>.Filter.Where(f => f._id == id));
        }
        public static void Delete<T>(this IMongoCollection<T> collection, string id) where T : DocumentBase
        {
            collection.UpdateOne(Builders<T>.Filter.Where(f => f._id == id), Builders<T>.Update.Set(s => s.IsDelete, 1));
        }
        public static List<T> GetByIds<T>(this IMongoCollection<T> collection, IEnumerable<string> ids) where T : DocumentBase
        {
            return collection.Find(Builders<T>.Filter.In(doc => doc._id, ids)).ToList();
        }
        public static void UpsertOne<T>(this IMongoCollection<T> collection, T item) where T : DocumentBase
        {
            if (string.IsNullOrWhiteSpace(item._id))
                collection.InsertOne(item);
            else
                collection.ReplaceOne(Builders<T>.Filter.Where(f => f._id == item._id), item);
        }
    }
}
